using System;
using System.Collections.Generic;
using System.IO;
using Newtonsoft.Json.Linq;

namespace JsonRpcGen.ParameterHandler
{
    internal class OverloadParamHandler : ParamHandler
    {
        List<ParamHandler> Params = new List<ParamHandler>();

        public OverloadParamHandler(string name, JToken parameter, Dictionary<string, string> replacements, string methodName)
            : base(name, "")
        {

            var types = parameter["type"];
            var counter = 0;
            Params.Add(new NoneParamHandler());
            foreach (var type in types)
            {
                if (type["type"]!=null && type["type"].ToString() == "null")
                {
                    continue;
                }
                
                ParamHandler paramHandler;

                counter++;
                try
                {
                    paramHandler = ParamsHandler.GetParamHandler(type, name, replacements, methodName,
                                                                 methodName + name + counter, methodName + name);
                }
                catch (Exception)
                {
                    counter--;
                    continue;
                }
                Params.Add(paramHandler);
                if (paramHandler is OverloadParamHandler)
                {
                    throw new NotImplementedException();
                }
            }
        }

        public int Count
        {
            get { return Params.Count; }
        }

        public void SetOverload(int overload)
        {
            Name = Params[overload].Name;
            OriginalName = Params[overload].OriginalName;
            Type = Params[overload].Type;
            WriteAction = Params[overload].WriteType;
            GetDefaultAction = Params[overload].GetDefault;
        }

        protected Func<string> GetDefaultAction { get; set; }

        Action<StreamWriter, Dictionary<string, string>> WriteAction;
        
        public override void WriteType(StreamWriter writer, Dictionary<string, string> replacements)
        {
            WriteAction(writer, replacements);
        }

        public override string GetDefault()
        {
            return GetDefaultAction();
        }
    }
}